/*
 * @Descripttion: 
 * @Version: 
 * @Author: 王传宝
 * @Date: 2023-02-27 14:39:03
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-03-02 16:50:29
 */
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { Button, List, SearchBar } from 'antd-mobile'
import Style from './Search.module.scss'
import { useSelector, useDispatch } from 'react-redux'
import { changeHistory, clearHistory, changeKeyword, changeSearchInfo } from '@/store/slices/searchSlice'
import { useNavigate } from 'react-router-dom'


const SearchView = () => {
  const [flag, setFlag] = useState(true)
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const histories = useSelector((state: any) => {
    return state.searchSlice.histories
  })

  const getSearchInfo = (key: any) => {
    return axios({
      url: '/xhr/search/search.json',
      method: 'get',
      params: {
        'csrf_token': "fbfcd0065626a539237fec01d5a340d8",
        '__timestamp': "autoComplete",
        'keyword': key,
        'sortType': 0,
        'descSorted': false,
        'categoryId': 0,
        'matchType': 0,
        'floorPrice': -1,
        'upperPrice': -1,
        'size': 40,
        'itemId': 0,
        'stillSearch': false,
        'searchWordSource': 5,
        'needPopWindow': true,
        '_stat_search': "history",
      }
    })
  }

  const [placeholder, setPlaceholder] = useState('')
  const [btns, setBtns] = useState([])
  const [search, setSearch] = useState([])
  useEffect(() => {
    axios({
      url: "/xhr/search/init.json",
      method: "post",
      params: {
        "csrf_token": "9978793b25933937f8071530b38ff35f"
      },
    }).then(res => {
      console.log(res);
      setBtns(res.data.data.hotKeywordVOList)
      setPlaceholder(res.data.data.defaultKeyword.keyword)
    })
  }, [])


  console.log("search-test")
  console.log("woshizuishuaide")
  console.log("dashuaige")
  return (
    <div className={Style.wrapper}>
      <SearchBar placeholder={placeholder} onChange={(info) => {
        axios({
          url: "/xhr/search/searchAutoComplete.json?csrf_token=9978793b25933937f8071530b38ff35f",
          method: "post",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          data: {
            keywordPrefix: info
          }
        }).then(res => {
          console.log(res)
          return setSearch(res.data.data)
        })
      }} showCancelButton={() => true} onCancel={() => { navigate(-1) }} />

      {
        flag && <div>
          {
            search.length == 0 ? (<div>
              <div>
                {
                  !!histories.length && <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', paddingTop: '5px' }}>
                      <p style={{ fontSize: '14px', color: "#999", marginTop: '5px' }}>历史记录</p>
                      <p style={{ fontSize: '14px', color: "#999", marginTop: '5px' }} onClick={() => {
                        dispatch(clearHistory())
                      }}>清空历史记录</p>
                    </div>

                    {
                      history.length != 0 && histories.map((val: any, index: number) => {
                        return <Button style={{ margin: '5px', fontSize: '12px', color: 'black', borderColor: 'black' }} key={index} color='primary' fill='outline' onClick={() => {
                          dispatch(changeKeyword(val))
                          getSearchInfo(val).then((res: any) => {
                            console.log(res)
                            if (res.data.code === '200') {
                              dispatch(changeSearchInfo(JSON.stringify(res)))
                              navigate('/search/searchDeatil')
                              dispatch(changeHistory(val))
                            }
                          })

                        }}>{val}</Button>
                      })
                    }
                  </div>
                }
              </div>

              <p style={{ fontSize: '16px', color: "#999", marginTop: '5px' }}>热门搜索</p>
              {/* 热门 */}
              <div className={Style.btns}>
                {
                  !!btns && btns.map((val: any, index) => {
                    return <Button style={{ margin: '5px', fontSize: '12px', color: 'black', borderColor: 'black' }} key={index} color='primary' fill='outline' onClick={() => {
                      dispatch(changeKeyword(val.keyword))
                      getSearchInfo(val.keyword).then((res: any) => {
                        if (res.data.code === '200') {
                          dispatch(changeSearchInfo(JSON.stringify(res)))
                          navigate('/search/searchDeatil')
                          dispatch(changeHistory(val.keyword))
                        }
                      })
                    }}>{val.keyword}</Button>

                  })
                }
              </div>

            </div>) :
              (
                <div>

                  {/* 搜索列表 */}
                  <List>
                    {
                      !!search && search.map((val, index) => {
                        return <List.Item key={index} onClick={(e: any) => {
                          dispatch(changeKeyword(e.target.innerText))
                          getSearchInfo(val).then((res: any) => {
                            if (res.data.code === '200') {
                              dispatch(changeSearchInfo(JSON.stringify(res)))
                              navigate('/search/searchDeatil')
                              dispatch(changeHistory(e.target.innerText))

                            }
                          })
                        }}>{val}</List.Item>
                      })
                    }
                  </List>
                </div>
              )
          }
        </div>
      }
    </div >
  )
}

export default SearchView

